package com.yunqiao.service.api.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.service.api.RedPacketService;
import com.yunqiao.service.api.entity.RedPacketEntity;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.mapper.RedPacketMapper;
import com.yunqiao.service.api.mapper.UserMapper;
import com.yunqiao.service.api.vo.RedPacketEntityVo;
import com.yunqiao.service.api.vo.RedPacketVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("redPacketService")
public class RedPacketServiceImpl extends ServiceImpl<RedPacketMapper, RedPacketEntity> implements RedPacketService {

    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //各种查询条件的过滤,在此进行
        QueryWrapper<RedPacketEntity> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(MapUtil.getStr(params, "userId"))) {
            queryWrapper.eq("user_id", MapUtil.getLong(params, "userId"));
        }
        IPage<RedPacketVo> page = this.redPacketMapper.pageList(new Query<RedPacketEntity>(params).getPage(),queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public RedPacketVo details(Integer id) {
        return redPacketMapper.details(id);
    }

    @Override
    public void saveRed(RedPacketEntityVo redPacket) {
        //String userIds = redPacket.getUserIds();
        //String[] split = userIds.split(",");
        //先给定所有用户
        List<UserEntity> userEntities = userMapper.selectList(new QueryWrapper<>());
        for (UserEntity userEntity : userEntities) {
            RedPacketEntity redPacketEntity = new RedPacketEntity();
            redPacketEntity.setAmount(redPacket.getAmount());
            redPacketEntity.setStatus(AppConsts.RED_PACKAGE_STATUS_1);
            redPacketEntity.setUserId(userEntity.getId());
            redPacketMapper.insert(redPacketEntity);
        }
    }
}
